package com.ponhu.ea2.goodsCenter.provider.biz.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ponhu.ea2.common.basic.model.ResponseBean;
import com.ponhu.ea2.constants.CommonConstant;
import com.ponhu.ea2.constants.DictConstant;
import com.ponhu.ea2.dto.CloudTradePropertyDto;
import com.ponhu.ea2.dto.LogsForTextAddDto;
import com.ponhu.ea2.dto.PhInventoryAccessoryDto;
import com.ponhu.ea2.dto.PhInventoryForCloudTradeDto;
import com.ponhu.ea2.entity.*;
import com.ponhu.ea2.enums.*;
import com.ponhu.ea2.goodsCenter.provider.biz.BaseInfoGenerateService;
import com.ponhu.ea2.goodsCenter.provider.biz.CloudTradeCoreService;
import com.ponhu.ea2.goodsCenter.provider.biz.InvokeStockCenterInterfaceService;
import com.ponhu.ea2.goodsCenter.provider.biz.OperationRecordLogsCoreService;
import com.ponhu.ea2.goodsCenter.provider.mapper.PhSysDictItemMapper;
import com.ponhu.ea2.goodsCenter.provider.service.*;
import com.ponhu.ea2.goodsCenter.provider.utils.CommonUtils;
import com.ponhu.ea2.service.facade.CommonApiService;
import com.ponhu.ea2.service.facade.GoodsCenterForThirdPartyService;
import com.ponhu.ea2.service.facade.InventoryApiService;
import com.ponhu.ea2.stockcenter.service.bms.StockForGoodsCenterService;
import com.ponhu.ea2.support.exception.BusinessRuntimeException;
import com.ponhu.ea2.vo.PhPropertyEditVo;
import io.netty.util.concurrent.FastThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import static com.ponhu.ea2.constants.CommonConstant.CATEGORY_LEVEL_3;
import static com.ponhu.ea2.enums.InventoryChannelEnum.CLOUD_TRADE_JOINT_CONSIGNMENT;
import static com.ponhu.ea2.enums.ResponseCodeEnum.INVENTORY_CREATE_EXCEPTION_800220;
import static com.ponhu.ea2.enums.ResponseCodeEnum.MATERIAL_CREATE_EXCEPTION_800402;

/**
 * 云商商品审核通过后，分发商品数据至各个业务系统
 *
 * @author Wang
 * @date 2021/11/19 4:28 下午
 */
@Slf4j
@Service
public class CloudTradeCoreServiceImpl implements CloudTradeCoreService {
    //是否添加云商商品至业务系统
    private static final FastThreadLocal<Boolean> isAddThreadLocal = new FastThreadLocal<>();
    //旧物料信息，可能为空
    private static final FastThreadLocal<Material> oldMaterialThreadLocal = new FastThreadLocal<>();
    //云商属性
    private static final FastThreadLocal<List<CloudTradePropertyDto>> propertyListThreadLocal = new FastThreadLocal<>();
    //附件数据
    private static final FastThreadLocal<List<PhInventoryAccessoryDto>> annexThreadLocal = new FastThreadLocal<>();
    //配件数据
    private static final FastThreadLocal<List<PhInventoryAccessoryDto>> accessoryThreadLocal = new FastThreadLocal<>();
    //系列ID
    private static final FastThreadLocal<Long> serialIdThreadLocal = new FastThreadLocal<>();
    //型号ID
    private static final FastThreadLocal<Long> modelIdThreadLocal = new FastThreadLocal<>();
    //物料属性
    private static final FastThreadLocal<List<PhMaterialPropertyValueMd>> materialPropertyThreadLocal = new FastThreadLocal<>();
    //货品属性
    private static final FastThreadLocal<List<PhInventoryPropertyValueMd>> inventoryPropertyThreadLocal = new FastThreadLocal<>();
    //保存数据库后的商品数据
    private static final FastThreadLocal<Goods> goodsThreadLocal = new FastThreadLocal<>();
    //保存数据库后的货品数据
    private static final FastThreadLocal<Inventory> inventoryThreadLocal = new FastThreadLocal<>();

    @Resource
    private InventoryApiService inventoryApiService;
    @Resource
    private PhSysDictItemMapper phSysDictItemMapper;
    @Resource
    private PhSysDictItemService phSysDictItemService;
    @Resource
    private PhInventoryAccessoryService inventoryAccessoryService;
    @Resource
    private MaterialService materialService;
    @Resource
    private PhMaterialPropertyValueMdService materialPropertyValueMdService;
    @Resource
    private PhInventoryPropertyValueMdService inventoryPropertyValueMdService;
    @Resource
    private CommonApiService commonApiService;
    @Resource
    private PhSeriesService phSeriesService;
    @Resource
    private PhModelService phModelService;
    @Resource
    private PhPropertyValueService phPropertyValueService;
    @Resource
    private BaseInfoGenerateService baseInfoGenerateService;
    @Resource
    private InvokeStockCenterInterfaceService invokeStockCenterInterfaceService;
    @Resource
    private PhCalculatePriceService phCalculatePriceService;
    @Resource
    private OperationRecordLogsCoreService operationRecordLogsCoreService;
    @Resource
    private CloudTradeGoodsService cloudTradeGoodsService;
    @Resource
    private GoodsCenterForThirdPartyService goodsCenterForThirdPartyService;
    @Resource
    private InventoryService inventoryService;
    @DubboReference(version = "1.0.0", check = false)
    private StockForGoodsCenterService stockForGoodsCenterService;


    /**
     * 云商商品数据分布至其它业务系统（商品中心、胖总管、WMS）
     *
     * @param cloudTradeGoods
     */
    private PhInventoryForCloudTradeDto distributeCloudTradeGoods(CloudTradeGoods cloudTradeGoods) {
        try {
            isAddThreadLocal.set(true);
            //1.分发商品中心
            handleGoodsCenterData(cloudTradeGoods);

            //2.组装胖总管，WMS数据
            PhInventoryForCloudTradeDto inventoryForCloudTradeDto = getPonhuAndWMSData(cloudTradeGoods);

            //3. 分发初始化库存数据
            handleStockCenterData(cloudTradeGoods);
            return inventoryForCloudTradeDto;
        } finally {
            removeThreadLocalData();
        }
    }

    /**
     * 更新云商商品数据并分发至其它业务系统（商品中心、胖总管、WMS）
     *
     * @param cloudTradeGoods
     */
    private PhInventoryForCloudTradeDto updateDistributeCloudTradeGoods(CloudTradeGoods cloudTradeGoods) {
        try {
            isAddThreadLocal.set(false);
            //1.分发商品中心
            handleGoodsCenterData(cloudTradeGoods);

            //2. 增加可售虚拟库存
            stockForGoodsCenterService.addOneVirtualSalesStockData(Collections.singletonList(cloudTradeGoods.getChannelGoodsCode()));

            //3.组装胖总管，WMS数据
            return getPonhuAndWMSData(cloudTradeGoods);
        } finally {
            removeThreadLocalData();
        }
    }

    private void removeThreadLocalData() {
        isAddThreadLocal.remove();
        serialIdThreadLocal.remove();
        modelIdThreadLocal.remove();
        materialPropertyThreadLocal.remove();
        propertyListThreadLocal.remove();
        annexThreadLocal.remove();
        accessoryThreadLocal.remove();
        inventoryPropertyThreadLocal.remove();
        goodsThreadLocal.remove();
        inventoryThreadLocal.remove();
        oldMaterialThreadLocal.remove();
    }

    private void handleStockCenterData(CloudTradeGoods cloudTradeGoods) {
        Goods goods = goodsThreadLocal.get();
        Inventory inventory = inventoryThreadLocal.get();

        CompletableFuture.runAsync(() -> {
            //以销定采
            boolean result;
            if (SalesModelEnum.JIT.getCode().equals(cloudTradeGoods.getSalesModel())) {
                result = invokeStockCenterInterfaceService.createAndInitUnRealStockData(
                        goods.getId(),
                        inventory.getId(),
                        inventory.getInventoryCode(), 1);
            } else {
                result = invokeStockCenterInterfaceService.createAndInitRealStockData(
                        goods.getId(),
                        inventory.getId(),
                        inventory.getInventoryCode());
            }
            if (result) {
                log.info("云商");
            }
        });
    }

    @Override
    public void dispatchDataToPonhuAndWMS(PhInventoryForCloudTradeDto joinDto) {
        CompletableFuture.runAsync(() -> {
            try {
                ResponseBean responseBean = goodsCenterForThirdPartyService.createGoodsAndInventoryForThirdpaerty(joinDto);
                if (responseBean.getCode() == CommonConstant.SUCCESS) {
                    log.info("云商数据分发胖总管，巨沃成功===>> 数据内容: {}" , JSONObject.toJSONString(joinDto));
                } else {
                    log.error("云商数据分发胖总管，巨沃失败：===>> 数据内容[{}] ===>> 返回结果：{}",
                            JSONObject.toJSONString(joinDto), JSONObject.toJSONString(responseBean));
                    //TODO 接钉钉
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("云商数据分发胖总管，巨沃异常:===> 数据内容：{} ===>> 异常信息：{}", JSONObject.toJSONString(joinDto), e.getMessage());
                //TODO 接钉钉
            }
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public PhInventoryForCloudTradeDto dispatchDataToGoodsCenter(CloudTradeGoods cloudTradeGoods) {
        //审核通过，将云商商品信息添加到商品中心，并同步给其它业务系统
        Inventory inventory = inventoryService.getInventoryByCode(cloudTradeGoods.getChannelGoodsCode());
        if(inventory == null ){
            //货品编码不存在，那么添加
            return this.distributeCloudTradeGoods(cloudTradeGoods);
        }else {
            //货品编码存在，那么更新
            return this.updateDistributeCloudTradeGoods(cloudTradeGoods);
        }
    }

    private PhInventoryForCloudTradeDto getPonhuAndWMSData(CloudTradeGoods cloudTradeGoods) {
        Goods goods = goodsThreadLocal.get();
        Inventory inventory = inventoryThreadLocal.get();

        PhInventoryForCloudTradeDto joinDto = new PhInventoryForCloudTradeDto();
        joinDto.setShopId(Objects.toString(cloudTradeGoods.getAccountId(), null));
        joinDto.setInventoryCode(cloudTradeGoods.getChannelGoodsCode());
        joinDto.setWarehousingPrice(inventory.getWarehousePrice());
        joinDto.setCostPrice(inventory.getInventoryCost());
        joinDto.setSupplyPrice(goods.getSupplyTaxPrice());
        joinDto.setSalesPriceGuidance(goods.getSaleTaxPrice());
        joinDto.setMaterialId(Objects.toString(inventory.getMaterialId(), null));
        joinDto.setIsTwoLuxury(inventory.getIsSecondhand());
        joinDto.setQuality(Objects.toString(cloudTradeGoods.getQuality(), null));
        joinDto.setCategoryId(Objects.toString(cloudTradeGoods.getCategoryId(), null));
        joinDto.setInventoryChannel(inventory.getInventoryChannel());
        joinDto.setSourceChannel(inventory.getSourceChannel());
        joinDto.setPurchasePrice(cloudTradeGoods.getPurchasePrice());
        joinDto.setWarehousingMethodId(Objects.toString(cloudTradeGoods.getInWay(), null));
        joinDto.setGoodsOwnerId(Objects.toString(cloudTradeGoods.getInventoryOwner(), null));
        joinDto.setFirstProcurementChannel(Objects.toString(cloudTradeGoods.getFirstPurchaseChannel(), null));
        joinDto.setSecondProcurementChannel(Objects.toString(cloudTradeGoods.getSecondPurchaseChannel(), null));
        joinDto.setImages(cloudTradeGoods.getDetailImage());
        joinDto.setBrandId(Objects.toString(cloudTradeGoods.getBrandId(), null));
        joinDto.setSalesModel(Objects.toString(cloudTradeGoods.getSalesModel(), null));
        joinDto.setAnnexs(String.join(",", Arrays.asList(cloudTradeGoods.getAnnex(), cloudTradeGoods.getAccessory())));
        joinDto.setInventory(inventory);
        joinDto.setIsUpdate(isAddThreadLocal.get() ? YesOrNoEnum.NO.getCode() : YesOrNoEnum.YES.getCode());

        //设置属性
        if( CollectionUtils.isNotEmpty(propertyListThreadLocal.get())){
            Map<String, String> collect = propertyListThreadLocal.get().stream().collect(Collectors.toMap(CloudTradePropertyDto::getName, CloudTradePropertyDto::getValue));
            joinDto.setPropertyMap(collect);
        }

        return joinDto;


    }

    private void handleGoodsCenterData(CloudTradeGoods cloudTradeGoods) {
        //属性解析
        parseCloudTradeProperty(cloudTradeGoods);
        //配件、附件解析
        parseAccessoryAndAnnex(cloudTradeGoods);

        //1.处理物料数据
        Material material = handleMaterialData(cloudTradeGoods);
        //2. 处理货品数据
        handleInventoryAndGoodsData(cloudTradeGoods, material);
        //3. 将物料编码更新至云商商品
        handleCloudTradeGoodsMaterialCode(cloudTradeGoods, material);

    }

    private void handleCloudTradeGoodsMaterialCode(CloudTradeGoods cloudTradeGoods, Material material) {
        if (cloudTradeGoods.getMaterialCode() == null) {
            //将新创建的物料编码更新至云商商品
            cloudTradeGoodsService.updateCloudTradeGoodsMaterialCode(cloudTradeGoods.getChannelGoodsCode(), material.getMaterialCode());
        }
    }

    private void parseAccessoryAndAnnex(CloudTradeGoods cloudTradeGoods) {
        if (StringUtils.isNotBlank(cloudTradeGoods.getAnnex())) {
            List<String> annexList = Arrays.asList(cloudTradeGoods.getAnnex().split(CommonConstant.SEPARATOR));

            //查询所有附件数据
            List<PhSysDictItem> dictItemList = phSysDictItemService.getDictItemsByType(DictConstant.INVENTORY_ANNEX);

            List<PhSysDictItem> resultList = new ArrayList<>();

            for (PhSysDictItem sysDictItem : dictItemList) {
                annexList.stream().filter(f -> sysDictItem.getLabel().equals(f)).findFirst().ifPresent(data -> resultList.add(sysDictItem));
            }


            List<PhInventoryAccessoryDto> annexDtoList = getPhInventoryAccessoryDtos(resultList);
            annexThreadLocal.set(annexDtoList);
        }

        if (StringUtils.isNotBlank(cloudTradeGoods.getAccessory())) {
            List<String> accessoryList = Arrays.asList(cloudTradeGoods.getAccessory().split(CommonConstant.SEPARATOR));

            //查询所有附件数据
            List<PhSysDictItem> dictItemList = phSysDictItemService.getDictItemsByType(DictConstant.INVENTORY_ACCESSORY);

            List<PhSysDictItem> resultList = new ArrayList<>();

            for (PhSysDictItem sysDictItem : dictItemList) {
                accessoryList.stream().filter(f -> sysDictItem.getLabel().equals(f)).findFirst().ifPresent(data -> resultList.add(sysDictItem));
            }

            List<PhInventoryAccessoryDto> accessoryDtoList = getPhInventoryAccessoryDtos(resultList);
            accessoryThreadLocal.set(accessoryDtoList);
        }
    }

    private List<PhInventoryAccessoryDto> getPhInventoryAccessoryDtos(List<PhSysDictItem> resultList) {
        return resultList.stream().map(i -> {
            PhInventoryAccessoryDto accessoryDto = new PhInventoryAccessoryDto();

            Integer dictItemValue = null;
            try {
                dictItemValue = i.getValue() == null ? null : Integer.parseInt(i.getValue());
            } catch (NumberFormatException e) {
                //nothing to do
            }

            accessoryDto.setDictType(i.getType());
            accessoryDto.setDictItemValue(dictItemValue);
            accessoryDto.setDictItemLabel(i.getLabel());
            return accessoryDto;
        }).collect(Collectors.toList());
    }

    private void parseCloudTradeProperty(CloudTradeGoods cloudTradeGoods) {
        if (cloudTradeGoods.getMaterialCode() != null) {
            //获取旧物料信息
            Material oldMaterial = materialService.getOneMaterialByCode(cloudTradeGoods.getMaterialCode());
            oldMaterialThreadLocal.set(oldMaterial);
        }

        if (StringUtils.isBlank(cloudTradeGoods.getProperties())) {
            return;
        }

        List<CloudTradePropertyDto> propertyList = null;
        try {
            propertyList = JSONArray.parseArray(cloudTradeGoods.getProperties(), CloudTradePropertyDto.class);
        } catch (Exception e) {
            //nothing to do
        }

        if (CollectionUtils.isEmpty(propertyList)) {
            return;
        }

        propertyListThreadLocal.set(propertyList);

        //型号与系列
        CloudTradePropertyDto modelProperty = propertyList.stream().filter(f -> "型号".equals(f.getName())).findFirst().orElse(null);
        CloudTradePropertyDto serialProperty = propertyList.stream().filter(f -> "系列".equals(f.getName())).findFirst().orElse(null);

        handleSerialProperty(serialProperty, cloudTradeGoods);
        handleModelProperty(modelProperty, cloudTradeGoods);


        //物料属性
        parseMaterialProperty(cloudTradeGoods, propertyList);
        //货品属性
        parseInventoryProperty(cloudTradeGoods, propertyList);
    }

    private void parseInventoryProperty(CloudTradeGoods cloudTradeGoods, List<CloudTradePropertyDto> propertyList) {
        List<PhPropertyEditVo> props = commonApiService.getAllInventoryProps(CATEGORY_LEVEL_3, cloudTradeGoods.getCategoryId());
        if (CollectionUtils.isEmpty(props)) {
            return;
        }

        //根据商品中心已有的物料属性、值进行匹配，当属性名称与值都匹配上时组装物料属性中间表
        List<PhInventoryPropertyValueMd> inventoryPropertyValueMdList = new ArrayList<>();

        for (PhPropertyEditVo prop : props) {
            String propName = prop.getPonhuName() == null ? prop.getName() : prop.getPonhuName();
            CloudTradePropertyDto propertyDto = propertyList.stream().filter(f -> f.getName().equals(propName)).findFirst().orElse(null);

            if (propertyDto == null) {
                continue;
            }

            Long propertyValueId = null;
            String propertyValueStr = null;

            switch (Objects.requireNonNull(InputMethodTypeEnum.getInputMethodType(prop.getInputMethod()))) {
                case INPUT:
                case TEXTAREA:
                    propertyValueStr = propertyDto.getValue();
                    break;
                case SELECT:
                case RADIO:
                case CHECKBOX:
                case MULTIPLE_SELECT:
                    List<PhPropertyValue> valuesByPropIds = phPropertyValueService.getValuesByPropIds(Collections.singletonList(prop.getId()));

                    PhPropertyValue propertyValue = valuesByPropIds.stream().filter(f -> f.getValue().equals(propertyDto.getValue())).findFirst().orElse(null);
                    if (propertyValue == null) {
                        continue;
                    }
                    propertyValueId = propertyValue.getId();
                    propertyValueStr = propertyValue.getValue();
                    break;
            }

            if (StringUtils.isNotBlank(propertyValueStr)) {
                //有属性，有值，那么生成物料属性中间表数据
                PhInventoryPropertyValueMd inventoryPropertyValueMd = new PhInventoryPropertyValueMd();
                inventoryPropertyValueMd.setPropertyId(prop.getId());
                inventoryPropertyValueMd.setPropertyName(prop.getName());
                inventoryPropertyValueMd.setValueId(propertyValueId);
                inventoryPropertyValueMd.setPropertyValue(propertyValueStr);

                inventoryPropertyValueMdList.add(inventoryPropertyValueMd);
            }
        }

        if (CollectionUtils.isNotEmpty(inventoryPropertyValueMdList)) {
            inventoryPropertyThreadLocal.set(inventoryPropertyValueMdList);
        }
    }

    private void parseMaterialProperty(CloudTradeGoods cloudTradeGoods, List<CloudTradePropertyDto> propertyList) {
        List<PhPropertyEditVo> props = commonApiService.getAllMaterialProps(CATEGORY_LEVEL_3, cloudTradeGoods.getCategoryId());
        if (CollectionUtils.isEmpty(props)) {
            return;
        }

        //根据商品中心已有的物料属性、值进行匹配，当属性名称与值都匹配上时组装物料属性中间表
        List<PhMaterialPropertyValueMd> materialPropertyValueMdList = new ArrayList<>();

        for (PhPropertyEditVo prop : props) {
            String propName = prop.getPonhuName() == null ? prop.getName() : prop.getPonhuName();
            CloudTradePropertyDto propertyDto = propertyList.stream().filter(f -> f.getName().equals(propName)).findFirst().orElse(null);

            if (propertyDto == null) {
                continue;
            }

            Long propertyValueId = null;
            String propertyValueStr = null;

            switch (Objects.requireNonNull(InputMethodTypeEnum.getInputMethodType(prop.getInputMethod()))) {
                case INPUT:
                case TEXTAREA:
                    propertyValueStr = propertyDto.getValue();
                    break;
                case SELECT:
                case RADIO:
                case CHECKBOX:
                case MULTIPLE_SELECT:
                    List<PhPropertyValue> valuesByPropIds = phPropertyValueService.getValuesByPropIds(Arrays.asList(prop.getId()));

                    PhPropertyValue propertyValue = valuesByPropIds.stream().filter(f -> f.getValue().equals(propertyDto.getValue())).findFirst().orElse(null);
                    if (propertyValue == null) {
                        continue;
                    }
                    propertyValueId = propertyValue.getId();
                    propertyValueStr = propertyValue.getValue();
                    break;

            }

            if (StringUtils.isNotBlank(propertyValueStr)) {
                //有属性，有值，那么生成物料属性中间表数据
                PhMaterialPropertyValueMd materialPropertyValueMd = new PhMaterialPropertyValueMd();
                materialPropertyValueMd.setPropertyId(prop.getId());
                materialPropertyValueMd.setPropertyName(prop.getName());
                materialPropertyValueMd.setValueId(propertyValueId);
                materialPropertyValueMd.setPropertyValue(propertyValueStr);

                materialPropertyValueMdList.add(materialPropertyValueMd);
            }
        }

        if (CollectionUtils.isNotEmpty(materialPropertyValueMdList)) {
            materialPropertyThreadLocal.set(materialPropertyValueMdList);
        }
    }


    private void handleInventoryAndGoodsData(CloudTradeGoods cloudTradeGoods, Material material) {
        Inventory inventory = getInventoryData(cloudTradeGoods);
        Goods goods = getGoodsData(cloudTradeGoods);
        inventory.setMaterialId(material.getId());
        inventory.setIsKpi(YesOrNoEnum.NO.getCode());
        //价格处理
        /*PriceVO priceVO = convertPrice(phCalculatePriceService.countPrice(inventory.getInventoryCost()));
        inventory.setWarehousePrice(priceVO.getWarehousingPrice());
        goods.setSaleTaxPrice(priceVO.getSalesPriceGuidance());
        goods.setSupplyTaxPrice(priceVO.getSupplyPrice());*/

        boolean result;
        if (isAddThreadLocal.get()) {
            result = inventoryApiService.saveInventoryAndGoods(inventory, goods);
            if (result) {
                //添加记录日志
                addRecordLog(CommonConstant.BUSINESS_TYPE_INVENTORY, inventory.getId(), "云商商品审核通过数据入库");
            }
        } else {
            result = inventoryApiService.updateInventoryAndGoods(inventory, goods);
            if (result) {
                addRecordLog(CommonConstant.BUSINESS_TYPE_INVENTORY, inventory.getId(), "云商商品审核通过数据更新");
            }
        }

        if (!result || inventory.getId() == null) {
            throw new BusinessRuntimeException(INVENTORY_CREATE_EXCEPTION_800220);
        }


        //获取货品属性中间表数据，并且插入数据库
        if (!isAddThreadLocal.get()) {
            //修改操作，删除所有货品属性数据
            inventoryPropertyValueMdService.deleteDataByInventoryId(inventory.getId());
        }

        //插入货品属性数据
        if (CollectionUtils.isNotEmpty(inventoryPropertyThreadLocal.get())) {
            List<PhInventoryPropertyValueMd> collect = inventoryPropertyThreadLocal.get().stream().map(
                    i -> i.setInventoryId(inventory.getId())).collect(Collectors.toList());

            inventoryPropertyValueMdService.saveBatch(collect);
        }

        //更新附件与配件数据
        inventoryAccessoryService.editInventoryAccessories(
                inventory, annexThreadLocal.get(), accessoryThreadLocal.get());

        goodsThreadLocal.set(goods);
        inventoryThreadLocal.set(inventory);
    }

    private Material handleMaterialData(CloudTradeGoods cloudTradeGoods) {
        //组装物料数据
        Material material = getMaterialData(cloudTradeGoods);

        //如果没有物料ID，那么创建新的物料
        if (material.getId() == null && cloudTradeGoods.getMaterialCode() == null) {
            boolean materialResult = materialService.save(material);
            if (!materialResult || material.getId() == null) {
                throw new BusinessRuntimeException(MATERIAL_CREATE_EXCEPTION_800402);
            }
            // 记录日志
            addRecordLog(CommonConstant.BUSINESS_TYPE_MASTERIAL, material.getId(), "云商物料创建成功");
        }
        if (cloudTradeGoods.getMaterialCode() != null && oldMaterialThreadLocal.get() != null) {
            //根据物料编码更新物料信息
            material.setMaterialCode(cloudTradeGoods.getMaterialCode());
            material.setId(oldMaterialThreadLocal.get().getId());
            materialService.updateById(material);
            // 记录日志
            addRecordLog(CommonConstant.BUSINESS_TYPE_MASTERIAL, material.getId(), "云商物料更新成功");

            //删除原有物料属性中间表数据
            materialPropertyValueMdService.removeMaterialProperty(material.getId());
        }

        //获取物料属性中间表数据，并且插入数据库
        if (CollectionUtils.isNotEmpty(materialPropertyThreadLocal.get())) {
            List<PhMaterialPropertyValueMd> collect = materialPropertyThreadLocal.get().stream().map(
                    i -> i.setMaterialId(material.getId())).collect(Collectors.toList());

            materialPropertyValueMdService.saveBatch(collect);
        }

        return material;
    }

    private void addRecordLog(String businessType, Long recordId, String content) {
        CompletableFuture.runAsync(() -> {
            LogsForTextAddDto logsForTextAddDto = new LogsForTextAddDto()
                    .setBusinessTable(businessType)
                    .setRecordId(recordId)
                    .setOperatorId(0L)
                    .setOperator("system")
                    .setTextContent(content);
            operationRecordLogsCoreService.addTextAddOperationRecordLogs(logsForTextAddDto);
        });
    }


    private void handleModelProperty(CloudTradePropertyDto modelProperty, CloudTradeGoods cloudTradeGoods) {
        if (modelProperty == null || StringUtils.isBlank(modelProperty.getValue()) || modelProperty.getValue().trim().equals("未知")) {
            return;
        }

        //如果没有物料，那么进行数据库查找
        if (oldMaterialThreadLocal.get() == null) {
            PhModel phModel = phModelService.getPhModelBySerialIdAndName(serialIdThreadLocal.get(), modelProperty.getValue().trim());

            if (phModel != null) {
                modelIdThreadLocal.set(phModel.getId());
                return;
            }
        }

        //添加或更新型号
        PhModel newModel = new PhModel();
        newModel.setModel(modelProperty.getValue().trim());
        newModel.setSeriesId(serialIdThreadLocal.get());
        newModel.setBrandId(cloudTradeGoods.getBrandId());
        newModel.setDataType(YesOrNoEnum.NO.getCode());

        if (oldMaterialThreadLocal.get() != null) {
            newModel.setId(oldMaterialThreadLocal.get().getModelId());
        }
        phModelService.saveOrUpdate(newModel);
        modelIdThreadLocal.set(newModel.getId());
    }

    private void handleSerialProperty(CloudTradePropertyDto serialProperty, CloudTradeGoods cloudTradeGoods) {
        if (serialProperty == null || StringUtils.isBlank(serialProperty.getValue()) || serialProperty.getValue().trim().equals("未知")) {
            return;
        }

        //如果没有物料，那么进行数据库查找
        if (oldMaterialThreadLocal.get() == null) {
            //与数据库进行匹配(根据品牌与值查找)
            PhSeries phSeries = phSeriesService.getPhSeriesByBrandIdAndName(cloudTradeGoods.getBrandId(), serialProperty.getValue().trim());

            if (phSeries != null) {
                //设置ID
                serialIdThreadLocal.set(phSeries.getId());
                return;
            }
        }

        //添加或更新系列
        PhSeries series = new PhSeries();
        series.setBrandId(cloudTradeGoods.getBrandId());
        series.setName(serialProperty.getValue().trim());
        series.setDataType(YesOrNoEnum.NO.getCode());//设置非标准数据

        if (oldMaterialThreadLocal.get() != null) {
            series.setId(oldMaterialThreadLocal.get().getSeriesId());
        }
        phSeriesService.saveOrUpdate(series);
        serialIdThreadLocal.set(series.getId());

    }

    private Material getMaterialData(CloudTradeGoods cloudTradeGoods) {
        //1.判断数据库是否已有该物料
        Material oldMaterial = materialService.getMaterialByCondition(cloudTradeGoods.getCategoryId(),
                cloudTradeGoods.getBrandId(),
                serialIdThreadLocal.get(), modelIdThreadLocal.get());

        if (oldMaterial != null) {
            return oldMaterial;
        }

        //2.数据库没有查到，那么组装新的物料数据
        Material material = new Material();
        //设置物料编码
        material.setMaterialCode(CommonUtils.createAndGetMaterialCode(cloudTradeGoods.getCategoryId()));
        material.setCategoryId(cloudTradeGoods.getCategoryId());
        material.setBrandId(cloudTradeGoods.getBrandId());
        material.setSeriesId(serialIdThreadLocal.get());
        material.setModelId(modelIdThreadLocal.get());
        material.setMainImage(cloudTradeGoods.getMainImage());
        material.setOfficialPrice(cloudTradeGoods.getMarketPrice());
        material.setUnit("件");
        material.setApplyCrowd(cloudTradeGoods.getApplyCrowd());
        material.setMaterialSource(MaterialSourceEnum.CLOUD_TRADE.getCode());
        material.setDataType(YesOrNoEnum.NO.getCode());
        //设置物料名称
        String materialName = baseInfoGenerateService.createAndGetMaterialName(material, materialPropertyThreadLocal.get());
        material.setMaterialName(materialName);

        return material;
    }

    private Goods getGoodsData(CloudTradeGoods cloudTradeGoods) {
        Goods goods = new Goods();
        goods.setGoodsCode(CommonUtils.createGoodsCode());
        goods.setType(GoodsTypeEnum.MATERIAL_OBJECT.getCode());
        goods.setGoodsName(cloudTradeGoods.getGoodsName());
        //设置商品上架状态
        goods.setGoodsStatus(GoodsStatusEnum.ON_SHELF.getCode());
        goods.setSaleTaxPrice(cloudTradeGoods.getAdvicePrice());
        goods.setSupplyTaxPrice(cloudTradeGoods.getSupplyPrice());

        return goods;
    }

    private Inventory getInventoryData(CloudTradeGoods cloudTradeGoods) {
        PhSysDictItem dictItem = phSysDictItemService.getDictItemByValue(DictConstant.CONDITION_TYPE,
                Objects.toString(cloudTradeGoods.getQuality(), ""));

        Inventory inventory = new Inventory();
        inventory.setInventoryCode(cloudTradeGoods.getChannelGoodsCode());
        inventory.setInventoryType(InventoryTypeEnum.MAIN_PRODUCT.getCode());
        inventory.setIsSecondhand(YesOrNoEnum.YES.getCode());
        inventory.setSourceChannel(cloudTradeGoods.getSourceChannel());
        inventory.setCategoryId(cloudTradeGoods.getCategoryId());
        inventory.setBrandId(cloudTradeGoods.getBrandId());
        inventory.setInventoryName(cloudTradeGoods.getGoodsName());
        inventory.setMainImage(cloudTradeGoods.getMainImage());
        inventory.setDetailImage(cloudTradeGoods.getDetailImage());
        inventory.setQuality(cloudTradeGoods.getQuality());
        inventory.setQualityValue(dictItem == null ? "" : dictItem.getLabel());
        inventory.setProvenance(cloudTradeGoods.getProvenance());
        //云商采购价=商品中心货品成本
        inventory.setInventoryCost(cloudTradeGoods.getPurchasePrice());
        inventory.setWarehousePrice(cloudTradeGoods.getInPrice());
        inventory.setFlaw(cloudTradeGoods.getFlaw());
        inventory.setRemarks(cloudTradeGoods.getRemarks());
        inventory.setInventoryChannel(CLOUD_TRADE_JOINT_CONSIGNMENT.getCode());
        inventory.setSalesModel(cloudTradeGoods.getSalesModel());
        inventory.setYear(cloudTradeGoods.getGoodsYear());
        inventory.setBaseMap(YesOrNoEnum.NO.getCode());
        return inventory;
    }
}
